package dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.springframework.stereotype.Repository;

import pojo.Customer;
import dao.CustomerDao;

@Repository(value="customerDao")
public class CustomerDaoImpl implements CustomerDao {
	@Resource(name = "ds1")
	private DataSource ds;

	@Override
	public Customer addCustomer(Customer c) {
		String sql = "insert into customer (id,cname,psd,age) values(?,?,?,?)";
		Connection con = null;
		PreparedStatement pst = null;
		try {
			con = ds.getConnection();
			pst = con.prepareStatement(sql);
			pst.setString(1, c.getId());
			pst.setString(2, c.getCname());
			pst.setString(3, c.getPassword());
			pst.setInt(4, c.getAge());
			pst.execute();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				pst.close();
				con.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return c;
	}

	@Override
	public Customer findCustomer(String cname, String psd) {
		Customer c=null;
		String sql = "select * from customer where cname=? and psd=?";
		Connection con = null;
		PreparedStatement pst = null;
		ResultSet rs=null;
		try {
			con = ds.getConnection();
			pst = con.prepareStatement(sql);
			pst.setString(1, cname);
			pst.setString(2, psd);
			rs=pst.executeQuery();
			if(rs.next()){
				c=new Customer();
				c.setId(rs.getString("id"));
				c.setCname(rs.getString("cname"));
				c.setAge(rs.getInt("age"));
				
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				rs.close();
				pst.close();
				con.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		

		return c;
	}

}





